<template>
  <el-upload
      :action="uploadData.url"
      :headers="uploadData.headers"
      :data="{ accept: acceptTypes, maxSize: maxFileSize }"
      :on-exceed="handleExceed"
      :before-upload="handleBeforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :show-file-list="false"
  >
    <el-button slot="trigger" size="small" type="primary">导入excel</el-button>
  </el-upload>
</template>

<script>

export default {
  name: 'ExcelUploader',
  props: {
    acceptTypes: {
      type: Array,
      default: () => ['.xlsx', '.xls']
    },
    maxFileSize: {
      type: Number,
      default: () => 20 * 1024 * 1024 // 20MB
    },
    headers: {
      type: Object,
      default: () => ({Authorization: JSON.parse(localStorage.getItem('vuex')).accessToken}),
    },
    url: String, // 父组件传递的上传地址
  },
  data() {
    return {
      uploadData: {
        headers: this.headers,
        url: this.url,
      },
    };
  },
  methods: {
    handleExceed() {
      this.$message.warning(`文件大小不能超过${this.maxFileSize / 1024 / 1024}MB`);
    },
    handleBeforeUpload(file) {
      const fileType = file.name.substring(file.name.lastIndexOf('.'));
      if (!this.acceptTypes.includes(fileType)) {
        this.$message.error(`只能上传${this.acceptTypes.join(',')}格式的文件`);
        return false;
      }
      return true;
    },
    handleSuccess(response) {
      console.log(response)
      if (response.code === 20000) {
        this.$message.success('上传成功');
      } else {
        this.$message.error('上传失败');
      }
    },
    handleError(error) {
      console.log(error)
      if (error.response) {
        this.$message.error(`上传失败：${error.response.data.message}`);
      } else {
        this.$message.error(`上传失败：${error.message}`);
      }
    }
  }
};
</script>